import React, { useState } from 'react';
import { Drawer, Spin, Timeline, message } from 'antd';
import { DownSquareOutlined, UpSquareOutlined } from '#/utils/antdIcons.js';
import InfiniteScroll from 'react-infinite-scroller';
import moment from 'moment';

import { HttpCode } from '#/utils/contacts.js';
import { TRDefault } from '@/components/index.js';
import planIcon from '@/assets/img/plan_icon.png';

import type { IOperationLogDataListType } from '../../type';
import { ILogType } from '../../type';
import { postQueryOperateLog } from '../../service';
import { operateTypeMap } from '../../dictionary';
import styles from './index.less';

interface IProps {
  /**
   * 是否显示抽屉
   */
  visible?: boolean;
  /**
   * 关闭函数
   */
  onClose?: () => void;
}

const OperationLog = (props: IProps) => {
  const { visible = false, onClose } = props;
  const [loading, setLoading] = useState<boolean>(false);
  const [error, setError] = useState<boolean>(false);
  const [isLoading, setIsLoading] = useState<boolean>(false);
  const [hasMore, setHasMore] = useState<boolean>(true);
  const [total, setTotal] = useState<number>(0);
  const [data, setData] = useState<IOperationLogDataListType[]>([]);

  // 初始化数据
  const fetchData = async () => {
    setLoading(true);
    setError(false);
    const res = await postQueryOperateLog({
      current: 1,
      size: 50,
    });
    if (res && res.statusCode === HttpCode.SUCCESS) {
      const _data = (res?.data?.records || []).map(
        (item: IOperationLogDataListType, index: number) => ({
          ...item,
          id: index + 1,
          titles: item?.title?.split(','),
        }),
      );
      setTotal(res?.data?.total ?? 0);
      setHasMore(res?.data?.total > 50 ? true : false);
      setData(_data);
      setError(false);
    } else {
      setError(true);
      message.info(res?.message || '系统异常');
    }
    setLoading(false);
  };

  // 取消
  const _onCancel = () => {
    onClose && onClose();
  };

  const loadMore = async (page: number) => {
    if (!hasMore) return;
    setIsLoading(true);
    setHasMore(total > 50 * (page + 1) ? true : false);
    const res = await postQueryOperateLog({
      current: page + 1,
      size: 50,
    });
    if (res && res.statusCode === HttpCode.SUCCESS) {
      const _data = (res?.data?.records || []).map(
        (item: IOperationLogDataListType, index: number) => ({
          ...item,
          id: index + 1 + (data.length ?? 0),
          titles: item?.title?.split(','),
        }),
      );
      setTotal(res?.data?.total ?? 0);
      setData([...data, ..._data]);
    } else {
      setData([...data]);
      message.info(res?.message || '系统异常');
    }
    setIsLoading(false);
  };

  const onSpread = (record: any) => {
    let _data = [...data];
    _data = _data.map((item) => {
      return {
        ...item,
        isSpread: item.id === record.id ? !item.isSpread : item?.isSpread,
      };
    });
    setData(_data);
  };

  React.useEffect(() => {
    fetchData();
  }, [visible]);

  return (
    <Drawer
      width={680}
      className={styles.operateLogModal}
      visible={visible}
      onClose={_onCancel}
      title={
        <div className={styles.titleDiv}>
          <img src={planIcon} className={styles.titleLogo} />
          <span className={styles.title}>操作日志</span>
        </div>
      }
      footer={null}
    >
      <div className={styles.container}>
        {loading ? (
          <Spin spinning={loading} />
        ) : error ? (
          <TRDefault type={'emptysm'} message={'系统异常'} />
        ) : data.length ? (
          <Spin spinning={isLoading} className={styles.spinloading}>
            <div className={styles.content}>
              <InfiniteScroll
                initialLoad={false}
                pageStart={0}
                loadMore={loadMore}
                hasMore={!loading && hasMore}
                useWindow={false}
                className={styles.infiniteScroll}
              >
                <Timeline>
                  {data.map((item, index: number) => {
                    return (
                      <Timeline.Item key={index}>
                        <div className={styles.timelineItem}>
                          <div className={styles.header}>
                            <div className={styles.title}>
                              <div className={styles.date}>
                                {moment(item.createTime).format('YYYY.MM.DD HH:mm:ss')}
                              </div>
                              <div className={styles.type}>
                                {item?.operateType &&
                                item?.type &&
                                operateTypeMap[item?.type][item?.operateType]
                                  ? operateTypeMap[item?.type][item?.operateType]
                                  : '-'}
                              </div>
                              <div className={styles.spread} onClick={() => onSpread(item)}>
                                {item?.isSpread ? (
                                  <UpSquareOutlined className={styles.spreadLogo} />
                                ) : (
                                  <DownSquareOutlined className={styles.spreadLogo} />
                                )}
                              </div>
                            </div>
                            <div className={styles.updateUser}>
                              <span>操作人：</span>
                              <span className={styles.operationUser}>
                                {item?.creatorName ?? '-'}
                              </span>
                            </div>
                          </div>
                          {item.isSpread && (
                            <div className={styles.bottom}>
                              {item?.type && item?.type === ILogType.INFO ? (
                                <div className={styles.menuName}>
                                  {item?.firstMenuName && (
                                    <span
                                      className={
                                        item?.secondMenuName
                                          ? styles.firstMenuName
                                          : styles.tabMenuName
                                      }
                                    >
                                      {item?.firstMenuName}
                                      {item?.secondMenuName && ' / '}
                                    </span>
                                  )}
                                  {item?.secondMenuName && (
                                    <span
                                      className={
                                        item?.tabMenuName
                                          ? styles.secondMenuName
                                          : styles.tabMenuName
                                      }
                                    >
                                      {item?.secondMenuName}
                                      {item?.tabMenuName && ' / '}
                                    </span>
                                  )}
                                  {item?.tabMenuName && (
                                    <span className={styles.tabMenuName}>{item?.tabMenuName}</span>
                                  )}
                                </div>
                              ) : (
                                <div className={styles.titles}>
                                  {item?.titles?.map((title: string) => {
                                    return (
                                      <div className={styles.title} key={title}>
                                        {title}
                                      </div>
                                    );
                                  })}
                                </div>
                              )}
                            </div>
                          )}
                        </div>
                      </Timeline.Item>
                    );
                  })}
                </Timeline>
              </InfiniteScroll>
            </div>
          </Spin>
        ) : (
          <TRDefault type={'emptysm'} message={'暂无数据'} />
        )}
      </div>
    </Drawer>
  );
};

export default OperationLog;
